package com.study.quiz.config;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CJunGod
 * @create 2020-03-08 20:01
 **/
@Controller
public class MainErrorContrller implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    public String handleError(ModelMap modelMap, HttpServletResponse response, HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (response.getStatus() == 404) {
            modelMap.put("errorCode", response.getStatus() + " 页面访问错误");
            modelMap.put("errorMsg", "哇偶，你所访问的页面已丢失");
        } else {
            modelMap.put("errorCode", status.value() + "错误,请稍后重试");
            modelMap.put("errorMsg", "错误信息：" + status.toString());
        }
        return "/common/error";
    }

    @Override
    public String getErrorPath() {

        return ERROR_PATH;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

}
